package com.sangmo.fts.process.inventory.service;

import com.sangmo.boot.framework.common.utils.DateUtils;
import com.sangmo.boot.framework.data.idm.IdentityManager;
import com.sangmo.boot.framework.plugin.dataview.crud.service.BaseViewService;
import com.sangmo.boot.framework.plugin.dataview.data.IDataViewRepo;
import com.sangmo.fts.common.authority.service.AuthorityEntityService;
import com.sangmo.fts.process.inventory.interfaces.IfLoanCreation;
import com.sangmo.fts.process.inventory.interfaces.IfRepaymentCreation;
import com.sangmo.fts.process.inventory.model.IfLoan;
import com.sangmo.fts.process.inventory.model.IfRepayment;
import com.sangmo.fts.process.inventory.repo.IfRepaymentRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class IfRepaymentEntityService extends AuthorityEntityService<IfRepayment> {

    @Autowired
    private IfRepaymentRepo ifRepaymentRepo;

    @Autowired
    private IdentityManager identityManager;

    @Autowired
    private IfLoanService ifLoanService;

    @Override
    protected IDataViewRepo<IfRepayment> getRepo() {
        return ifRepaymentRepo;
    }

    @Override
    protected void onCreate(IfRepayment entity, Object bo) {
        super.onCreate(entity, bo);
        IfRepaymentCreation creation = (IfRepaymentCreation) bo;
        IfLoan loan = ifLoanService.find(creation.getLoanId());
        entity.setCode(loan.getCode() + identityManager.next("IF_REPAYMENT", 3));
        entity.setPayId(loan.getApplyId());
        entity.setBankId(loan.getBankId());
    }

    @Override
    protected void afterCreated(IfRepayment entity, Object bo) {
        super.afterCreated(entity, bo);
        List<IfRepayment> repaymentList = ifRepaymentRepo.findByLoanId(entity.getLoanId());
        BigDecimal totalPaymentAmount = BigDecimal.ZERO;
        for (IfRepayment repayment : repaymentList) {
            totalPaymentAmount = totalPaymentAmount.add(repayment.getAmount());
        }
        totalPaymentAmount = totalPaymentAmount.add(entity.getAmount());
        ifLoanService.settle(entity.getLoanId(), totalPaymentAmount);
    }
}
